package com.orange.common.page;

/**
 * TODO
 *
 * @Author YWF
 * @Date 2025/8/19 16:58
 */

import com.baomidou.mybatisplus.core.metadata.IPage;
import lombok.Data;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 分页结果封装
 */
@Data
public class PageResult<T> {
    /**
     * 当前页码
     */
    private Long page;

    /**
     * 每页数量
     */
    private Long size;

    /**
     * 总记录数
     */
    private Long total;

    /**
     * 总页数
     */
    private Long pages;

    /**
     * 当前页数据
     */
    private List<T> records;

    /**
     * 是否有上一页
     */
    private Boolean hasPrevious;

    /**
     * 是否有下一页
     */
    private Boolean hasNext;

    /**
     * 从MyBatis-Plus分页对象转换
     */
    public static <T> PageResult<T> from(IPage<T> page) {
        PageResult<T> result = new PageResult<>();
        result.setPage(page.getCurrent());
        result.setSize(page.getSize());
        result.setTotal(page.getTotal());
        result.setPages(page.getPages());
        result.setRecords(page.getRecords());
        result.setHasPrevious(page.getCurrent() > 1);
        result.setHasNext(page.getCurrent() < page.getPages());
        return result;
    }


    /**
     * 转换记录类型
     *
     * @param converter 记录转换函数
     * @return 转换后的分页结果
     */
    public <R> PageResult<R> convert(Function<T, R> converter) {
        PageResult<R> result = new PageResult<>();
        result.setPage(this.page);
        result.setSize(this.size);
        result.setTotal(this.total);
        result.setPages(this.pages);
        result.setHasPrevious(this.hasPrevious);
        result.setHasNext(this.hasNext);

        if (this.records != null && !this.records.isEmpty()) {
            result.setRecords(
                    this.records.stream()
                            .map(converter)
                            .collect(Collectors.toList())
            );
        } else {
            result.setRecords(new ArrayList<>());
        }

        return result;
    }
}